/**
 * 树形目录管理模块
 */
class DetailManager {
    constructor() {
        this.table = null;
        this.layer = null;
        this.isLoading = false;
        this.contextMenu = null;
        this.selectedRowData = null;
        this.srcSelected = false;
        this.srcPath = '';
        this.srcCmd = '';
        this.currentPath = '';
        this.init();

    }

    init() {
        // 等待layui加载完成

        layui.use(['table', 'layer'], (table, layer) => {
            this.table = table;
            this.layer = layer;
            this.contextMenu = document.getElementById('contextMenu');
            this.currentPath = document.getElementById('detailCurrentPath').textContent;

            this.initFileTable();
            this.initContextMenu();
            this.bindButtons();
            this.bindTableToolbarEvents();

        });
    }

    // 绑定按钮
    bindButtons() {
        document.getElementById('refreshDetailBtn').addEventListener('click', () => {
            // this.loadDirectory();
            this.getFileListByPath(this.currentPath);
        });

        document.getElementById('detailCurrentPath').addEventListener('click', (e) => {
            this.layer.prompt({
                title: '请输入路径',
                value: e.target.textContent,
                formType: 0,
                maxlength: 255,
                minlength: 1,
                success: function(layero, index) {
                    // 修改整个弹窗宽度
                    layero.css('width', '600px');
                    // 修改输入框宽度
                    layero.find('.layui-layer-input').css('width', '500px');
                    // 弹开位置
                    layero.css('top', '300px');
                    // 弹开位置
                    layero.css('left', '400px');
                }
            }, (value, index, elem) =>{
                if(value === '') return elem.focus();

                // 打开文件
                this.getFileListByPath(value);

                // 关闭 prompt
                layer.close(index);
            });            
        })
    }


    // 加载文件列表
    loadDirectory() {
        const config = window.getConfig();
        if (!config) {
            this.layer.msg('请先输入配置');
            return;
        }
        
        this.showLoading(true);
        // 清空表格
        this.table.reload('fileTable', {
            data: [],
        });
        window.showStatusMessage('正在加载目录: ' + config.remotePath, 'info');

        const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
        const commandConfig = {
            cmd_event: "detail",
            params: [config.remotePath],
            hosts_key: [hostKey]
        };
        window.SocketClient.sendCommand(commandConfig);
    }

    // 通过事件重新加载目录
    getFileListByPath(path) {
        const config = window.getConfig();
        if (!config || !config.host) {
            return;
        }

        window.showStatusMessage('正在加载目录详情: ' + path, 'info');

        const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
        const commandConfig = {
            cmd_event: "detail",
            params: [path],
            hosts_key: [hostKey]
        };
        window.SocketClient.sendCommand(commandConfig);
    }


    handleEventResult(data) {
        this.showLoading(false);
        if (data.success){
            if ( data.cmd_event === 'detail') {
                // 将目录详情渲染到表格
                this.renderDirectory(data.data[0].content);
                // 更新当前目录
                this.currentPath = data.data[0].bash_path;
                document.getElementById('detailCurrentPath').textContent = this.currentPath;
                window.showStatusMessage(data.msg, 'success');
            } 
            else if (data.cmd_event === 'rename') {
                this.layer.msg('重命名成功', {icon: 1});
                window.showStatusMessage(data.msg, 'success');
                // 刷新当前目录
                this.getFileListByPath(this.currentPath);
                // 刷新树目录
                window.TreeManager.loadTreeWithPath(this.currentPath);
                this.showLoading(false);
            } 
            else if (data.cmd_event === 'mkdir') {
                this.layer.msg('创建目录成功', {icon: 1});
                window.showStatusMessage(data.msg, 'success');
                // 刷新当前目录
                this.getFileListByPath(this.currentPath);
                // 刷新树目录
                window.TreeManager.loadTreeWithPath(this.currentPath);
                this.showLoading(false);
            }else if (data.cmd_event === 'touch') {
                this.layer.msg('创建文件成功', {icon: 1});
                window.showStatusMessage(data.msg, 'success');
                // 刷新当前目录
                this.getFileListByPath(this.currentPath);
                // 刷新树目录
                window.TreeManager.loadTreeWithPath(this.currentPath);
                this.showLoading(false);
            }else if (data.cmd_event === 'delete') {
                this.layer.msg('删除成功', {icon: 1});
                window.showStatusMessage(data.msg, 'success');
                // 刷新当前目录
                this.getFileListByPath(this.currentPath);
                // 刷新树目录
                window.TreeManager.loadTreeWithPath(this.currentPath);
                this.showLoading(false);
            } else if (data.cmd_event === 'move') {
                this.layer.msg('移动成功', {icon: 1});
                window.showStatusMessage(data.msg, 'success');
                // 刷新当前目录
                this.getFileListByPath(this.currentPath);
                // 刷新树目录
                window.TreeManager.loadTreeWithPath(this.currentPath);
                this.showLoading(false);
            } else if (data.cmd_event === 'copy') {
                this.layer.msg('复制成功', {icon: 1});
                window.showStatusMessage(data.msg, 'success');
                // 刷新当前目录
                this.getFileListByPath(this.currentPath);
                // 刷新树目录
                window.TreeManager.loadTreeWithPath(this.currentPath);
                this.showLoading(false);
            } else if (data.cmd_event === 'chmod') {
                this.layer.msg('修改权限成功', {icon: 1});
                window.showStatusMessage(data.msg, 'success');
                // 刷新当前目录
                this.getFileListByPath(this.currentPath);
                this.showLoading(false);
            } 
            
            else {
                // this.layer.msg('事件执行成功', {icon: 1});
                window.showStatusMessage(data.msg, 'success');
            }


        }
        else {
            this.layer.msg('跳转失败', {icon: 2});
            window.showStatusMessage(data.msg, 'error');
        }
    }

    // 渲染目录列表
    renderDirectory(dirData) {
        console.log('dirData', dirData);
        this.table.reload('fileTable', {
            data: dirData,
            // loading: false
        });
    }

    // 初始化文件列表
    initFileTable() {
        this.table.render({
            elem: '#fileTable',
            cols: [[
                {type: 'radio', fixed: 'left', width: 50},
                {field: 'type', title: '类型', width: 80, sort: true, templet: (d) => this.renderFileType(d), unresize: true},
                {field: 'name', title: '文件名', width: 250, sort: true, templet: (d) => this.renderFileName(d)},
                {field: 'size', title: '大小', width: 120, sort: true, templet: (d) => this.renderFileSize(d)},
                {field: 'size_bytes', title: '字节数', width: 120, sort: true},
                {field: 'modified_time', title: '修改时间', width: 180, sort: true},
                {field: 'permissions', title: '权限', width: 120, templet: (d) => this.renderPermissions(d)},
                {field: 'owner', title: '所有者', width: 100, sort: true},
                {field: 'group', title: '用户组', width: 100, sort: true},
                {field: 'sort_key', title: 'sort_key', width: 100, sort: true},
            ]],
            data: [],
            skin: 'grid',
            page: false,
            loading: true,
            toolbar: this.renderToolbar(),
            defaultToolbar: ['filter'],
            height: 750,
            initSort: {
                field: 'sort_key',
                type: 'asc'
            },
            done:  () => {
                // 表格渲染完成后绑定右键事件
                setTimeout(() => {
                    const tableBody = document.querySelector('#fileTable + .layui-table-view .layui-table-body tbody');
                    if (tableBody) {
                        tableBody.addEventListener('contextmenu',  (e) => {
                            e.preventDefault();
                            
                            const tr = e.target.closest('tr[data-index]');
                            if (tr) {
                                const index = parseInt(tr.getAttribute('data-index'));
                                const tableData = this.table.cache['fileTable'];
                                const rowData = tableData[index];
                                
                                if (rowData) {
                                    // 选中该行
                                    this.table.setRowChecked('fileTable', {
                                        index: index,
                                        type: 'radio'
                                    });
                                    
                                    this.showContextMenu(e.clientX, e.clientY, rowData);
                                }
                            }
                        });
                    }
                }, 100);
            }
        });

        // 表格行单击事件
        this.table.on('row(fileTable)', (obj) => {
            var data = obj.data;
            this.selectedRowData = data;
            // this.layer.msg(`选中: ${data.name} (${data.type})`, {offset: '65px', time: 2000});
            obj.setRowChecked({type: 'radio'});
        });

         // 表格行双击事件
        this.table.on('rowDouble(fileTable)', (obj) => {
            var data = obj.data;
            if (data.type === '目录') {
                let newPath;
                if (this.currentPath.endsWith('/') || this.currentPath.endsWith('\\')) {
                    newPath = this.currentPath + data.name;
                } else {
                    const separator = this.currentPath.includes('\\') ? '\\' : '/';
                    newPath = this.currentPath + separator + data.name;
                }
                this.getFileListByPath(newPath);
            } else {
                // 打开文件
                window.EditorManager.loadFile(data.abs_path);
            }
        });
    }


    // =============== 自定义渲染函数 ==================
    renderFileName(d) {
        const iconClass = d.type === '目录' ? 'layui-icon-folder' : 'layui-icon-file';
        const iconColor = d.type === '目录' ? 'folder' : 'file';
        return `
            <div class="file-name-cell">
                <i class="layui-icon ${iconClass} file-icon ${iconColor}" style="vertical-align: middle; horizontal-align:middle"></i>
                <span>${d.name}</span>
            </div>
        `;
    }

    renderFileType(d) {
        const tagClass = d.type === '目录' ? 'folder' : 'file';
        return `<span class="type-tag ${tagClass}">${d.type}</span>`;
    }

    renderPermissions(d) {
        return `<span class="permissions">${d.permissions}</span>`;
    }

    renderFileSize(d) {
        return `<span class="file-size">${d.size}</span>`;
    }

    renderToolbar() {
        return `
            <div class="layui-btn-container">
                
                <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="parentDir">
                    <i class="layui-icon layui-icon-up"></i> 上级目录
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="getSelected">
                    <i class="layui-icon layui-icon-ok"></i> 获取选中项
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="createFolder">
                    <i class="layui-icon layui-icon-folder"></i> 新建文件夹
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="createFile">
                    <i class="layui-icon layui-icon-file"></i> 新建文件
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="terminal">
                    <i class="layui-icon layui-icon-layer"></i> 终端
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="transferFile">
                    <i class="layui-icon layui-icon-upload"></i> 文件传输
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="downloadFile">
                    <i class="layui-icon layui-icon-download-circle"></i> 下载文件
                </button>
                <div class="layui-input-inline">
                    <span>sudo模式</span>
                    <input type="checkbox" id="sudoCheckbox" name="switch4" lay-skin="switch" lay-text="开|关" lay-filter="switchTest">

                </div>

            </div>
        `;
    }


    // =============== 上下文菜单 ================
    initContextMenu() {
        // 点击其他地方隐藏菜单
        document.addEventListener('click',  (e) => {
            if (!this.contextMenu.contains(e.target)) {
                this.hideContextMenu();
            }
        });

        // 右键菜单项点击事件
        this.contextMenu.addEventListener('click',  (e) => {
            e.stopPropagation();
            const menuItem = e.target.closest('.context-menu-item');
            if (menuItem) {
                const action = menuItem.dataset.action;
                this.handleContextMenuAction(action);
                this.hideContextMenu();
            }
        });
    }

    // 处理右键菜单动作
    handleContextMenuAction(action) {
        if (!this.selectedRowData) return;
        
        const fileData = this.selectedRowData;
        
        switch(action) {
            case 'open':
                if (fileData.type === '目录') {
                    let newPath;
                    if (this.currentPath.endsWith('/') || this.currentPath.endsWith('\\')) {
                        newPath = this.currentPath + fileData.name;
                    } else {
                        const separator = this.currentPath.includes('\\') ? '\\' : '/';
                        newPath = this.currentPath + separator + fileData.name;
                    }
                    // 刷新目录
                    this.getFileListByPath(newPath);
                } else {
                    // 打开文件
                    window.EditorManager.loadFile(fileData.abs_path);
                }
                break;
            case 'rename':
                layer.prompt({
                    title: '重命名',
                    value: fileData.name,
                    maxlength: 255
                }, (newName, index) => {
                    layer.close(index);

                    const oldPath = fileData.abs_path;
                    // 提取文件的目录
                    const dirPath = oldPath.substring(0, oldPath.lastIndexOf('/') + 1);
                    const newPath = dirPath + newName;
                    // const newPath = oldPath.replace(fileData.name, newName);
                    window.showStatusMessage('正在重命名: ' + fileData.name, 'info');

                    this.sendCommand('rename',[oldPath, newPath]);
                });
                break;
            case 'copy':
                window.showStatusMessage(`复制文件: ${fileData.name} >> `, 'info');
                // 记录复制源文件
                this.srcSelected = true;
                document.getElementById('pasteBtn').classList.remove('layui-btn-disabled');
                this.srcPath = fileData.abs_path;
                this.srcCmd = 'copy';

                layer.msg(`复制文件: ${fileData.name}`, {icon: 1});
                break;
            case 'move':
                window.showStatusMessage(`移动文件: ${fileData.name} >> `, 'info');
                // 记录移动源文件
                this.srcSelected = true;
                document.getElementById('pasteBtn').classList.remove('layui-btn-disabled');
                this.srcPath = fileData.abs_path;
                this.srcCmd = 'move';

                layer.msg(`移动文件: ${fileData.name}`, {icon: 1});
                break;
            case 'paste':
                layer.msg(`粘贴文件: ${fileData.name}`, {icon: 1});
                // 检查是否有源文件

                if (this.srcPath === '') {
                    return;
                }
                //  发送粘贴请求到后端
                if (this.srcCmd === 'copy') {
                    this.sendCommand('copy',[this.srcPath, fileData.abs_path]);
                    window.showStatusMessage(`复制文件: ${this.srcPath} >> ${fileData.abs_path}`, 'info');

                } else if (this.srcCmd === 'move') {
                    window.showStatusMessage(`移动文件: ${this.srcPath} >> ${fileData.abs_path}`, 'info');
                    this.sendCommand('move',[this.srcPath, fileData.abs_path]);
                    // 更新粘贴按钮状态为禁用
                    this.srcSelected = false;
                    this.srcPath = '';
                    this.srcCmd = '';
                    document.getElementById('pasteBtn').classList.add('layui-btn-disabled');
                }
                break;
            case 'delete':
                layer.confirm(`确定要删除 "${fileData.name}" 吗？`, {
                    icon: 3,
                    title: '确认删除'
                }, (index) => {
                    layer.msg(`删除文件: ${fileData.name}`, {icon: 1});
                    layer.close(index);
                    //  发送删除请求到后端
                    this.sendCommand('delete',[fileData.abs_path]);
                });
                break;
            case 'permissions':
                // layer.alert(`
                //     <div style="text-align: left;">
                //         <p><strong>当前权限:</strong> ${fileData.permissions}</p>
                //         <p><strong>所有者:</strong> ${fileData.owner}</p>
                //         <p><strong>用户组:</strong> ${fileData.group}</p>
                //         <br>
                //         <p style="color: #999;">权限修改功能待实现...</p>
                //     </div>
                // `, {
                //     title: '修改权限 - ' + fileData.name,
                //     area: ['400px', '250px']
                // });
                

                layer.prompt({
                    title: '请输入数字以修改权限（如777）',
                    formType: 0,
                    maxlength: 3,
                    minlength: 3,
                    filter: /^\d{3}$/
                }, (value, index, elem) => {

                    if(value === '') return elem.focus();
                    
                    // 发送修改权限请求到后端
                    this.sendCommand('chmod',[value,fileData.abs_path]);

                    // 关闭 prompt
                    layer.close(index);
                });


                break;
        }
    }

    // 发送命令请求到后端
    sendCommand(cmd_event, params) {
        const config = window.getConfig();
        if (!config) {
            this.layer.msg('请先输入配置');
            return;
        }
        this.showLoading(true);
        window.showStatusMessage('正在执行命令: ' + cmd_event, 'info');
        const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
        const commandConfig = {
            cmd_event: cmd_event,
            params: params,
            hosts_key: [hostKey],
            sudo: document.getElementById('sudoCheckbox').checked
        };
        window.SocketClient.sendCommand(commandConfig);
    }


    // 显示右键菜单
    showContextMenu(x, y, rowData) {
        this.selectedRowData = rowData;
        
        // 调整菜单文本
        const openItem = this.contextMenu.querySelector('[data-action="open"]');
        openItem.innerHTML = `<i class="layui-icon layui-icon-ok-circle"></i>${rowData.type === '目录' ? '进入目录' : '打开文件'}`;
        
        // 显示菜单
        this.contextMenu.style.left = x + 'px';

        // 如果处于底部，调整位置
        if (y + this.contextMenu.offsetHeight > window.innerHeight) {
            y = window.innerHeight - this.contextMenu.offsetHeight;
        }
        this.contextMenu.style.top = y + 'px';
        this.contextMenu.style.display = 'block';
    }

    // 隐藏右键菜单
    hideContextMenu() {
        this.contextMenu.style.display = 'none';
    }

    // 获取当前选中的行数据
    getSelectedRowPath() {
        // return this.selectedRowData;
        this.table.on('row(fileTable)', (obj) => {
            var data = obj.data;
            this.selectedRowData = data;
            obj.setRowChecked({type: 'radio'});
        });
        if (this.selectedRowData) {
            if (this.selectedRowData.abs_path.endsWith('/..') || this.selectedRowData.abs_path.endsWith('/.')){
                return this.currentPath;
            }
            return this.selectedRowData.abs_path;
        }
        return this.currentPath;
    }


    // 头工具栏事件
    bindTableToolbarEvents() {
        this.table.on('toolbar(fileTable)', (obj) => {

                var checkStatus = this.table.checkStatus(obj.config.id);
                switch(obj.event){
                    case 'refresh':
                        loadDirectory(currentPath);
                        break;
                    case 'getSelected':
                        var data = checkStatus.data;
                        if (data.length === 0) {
                            layer.msg('请先选择一行数据', {icon: 0});
                        } else {
                            const fileInfo = data[0];
                            layer.alert(`
                                <div style="text-align: left;">
                                    <p><strong>文件名:</strong> ${fileInfo.name}</p>
                                    <p><strong>类型:</strong> ${fileInfo.type}</p>
                                    <p><strong>大小:</strong> ${fileInfo.size}</p>
                                    <p><strong>修改时间:</strong> ${fileInfo.modified_time}</p>
                                    <p><strong>权限:</strong> ${fileInfo.permissions}</p>
                                    <p><strong>所有者:</strong> ${fileInfo.owner}</p>
                                    <p><strong>用户组:</strong> ${fileInfo.group}</p>
                                </div>
                            `, {
                                title: '文件详细信息',
                                area: ['400px', '300px']
                            });
                        }
                        break;
                    case 'parentDir':

                        let newPath;
                        if (this.currentPath.endsWith('/') || this.currentPath.endsWith('\\')) {
                            newPath = this.currentPath + '..';
                        } else {
                            const separator = this.currentPath.includes('\\') ? '\\' : '/';
                            newPath = this.currentPath + separator + '..';
                        }
                        this.getFileListByPath(newPath);

                        break;              
                    case 'createFolder':
                        layer.prompt({
                            title: '创建文件夹',
                            value: '',
                            maxlength: 255
                        }, (dirname, index) => {
                            if (!dirname) return;
                            
                            const newPath = this.currentPath + '/' + dirname;

                            layer.close(index);
                            this.sendCommand('mkdir', [newPath]);
                        })
                        break;
                    case 'createFile':
                        this.layer.msg('创建文件成功', {icon: 1});

                        layer.prompt({
                            title: '创建文件',
                            value: '',
                            maxlength: 255
                        }, (filename, index) => {
                            if (!filename) return;
                            
                            const newPath = this.currentPath + '/' + filename;

                            layer.close(index);
                            this.sendCommand('touch', [newPath]);
                        })
                        break;
                    case 'terminal':
                        this.layer.msg('打开终端', {icon: 1});
                        break;
                    case 'transferFile':
                        this.layer.msg('文件传输', {icon: 1});
                        window.FileLoadsManager.renderTransferMenu();
                        break;
                    case 'downloadFile':
                        this.layer.msg('下载文件', {icon: 1});
                        // const checkStatus = this.table.checkStatus(obj.config.id);
                        var data = checkStatus.data;

                        var srcPath = "";
                        if (data.length === 0) {
                            srcPath = ""
                        } else {
                            const fileInfo = data[0];
                            srcPath = fileInfo.abs_path;
                        }
                        var srcIp = window.getConfig().host;
                        var srcUsername = window.getConfig().username;
                        var srcPassword = window.getConfig().password;
                        var destIp = '127.0.0.1';
                        var destPath = 'C:\\Users\\cheng.chen\\Downloads\\test';
                        var destUsername = 'root';
                        var destPassword = '123456';
                        var transferMode = 'scp';
                        window.FileDownloadManager.showDownloadDialog({
                            srcIp,
                            srcPath,
                            srcUsername,
                            srcPassword,
                            destIp,
                            destPath,
                            destUsername,
                            destPassword,
                            transferMode
                        });
                        

                        // window.FileDownloadManager.showDownloadDialog();

                        break;

                    }

            });
    }

    // 显示加载状态
    showLoading(show) {
        const loading = document.getElementById('loading-detail');
        this.isLoading = show;
        loading.style.display = show ? 'block' : 'none';
    }

}

// 创建全局TreeManager实例
window.DetailManager = new DetailManager();
